package ru.lenwp.operation.client;

import ru.lenwp.context.Context;
import ru.lenwp.model.Account;
import ru.lenwp.model.Client;
import ru.lenwp.model.OperationInfo;
import ru.lenwp.model.User;
import ru.lenwp.operation.Operation;
import ru.lenwp.util.ConsoleUtil;

/**
 * Created by Lenar on 14.08.2014.
 */
public class TransferThisClient implements Operation {

    private final Context context;

    public TransferThisClient(Context context) {
        this.context = context;
    }

    public void transferThisClient(Context context) {
        boolean performed = false;
        while (!performed) {
            Client client = (Client)context.getCurrentUser();
            if(client.getAccountList().isEmpty()){
                System.out.println("У такого клиента отсутствуют счета");
                return;
            }
            System.out.println("Выберите откуда перевести средства");
            for(int i = 1; i<=client.getAccountList().size(); i++){
                System.out.println(i+ ". " + client.getAccountList().get(i-1).getNumber() +
                        " " + client.getAccountList().get(i-1).getSum());
            }
            int accNumberMenu = ConsoleUtil.askMenuNumber();
            Account sourceAccount = client.getAccountList().get(accNumberMenu - 1);
            System.out.println("Введите номер счета");
            String accNumber = ConsoleUtil.askString();
            Account account = null;
            for (User user : context.getUserDao().allUser()) {
                if (user instanceof Client) {
                    for (Account currentAccount : ((Client) user).getAccountList()) {
                        if (currentAccount.getNumber() != null && accNumber.equals(currentAccount.getNumber())) {
                            account = currentAccount;
                            break;
                        }
                    }
                }
            }
            if (account != null) {
                while(true) {
                    double sum = ConsoleUtil.askDouble("Введите сумму, которую желаете положить на счет");
                    if (sourceAccount.getSum() >= sum) {
                        sourceAccount.setSum(sourceAccount.getSum() - sum);
                        account.setSum((sum + account.getSum()));
                        performed = true;
                        break;
                    }
                    System.out.println("Недостаточно средств для выполнения операции");
                }
            } else {
                System.out.println("Счета не существует");
            }
        }
    }

    @Override
    public OperationInfo execute() {
        transferThisClient(context);
        return null;
    }

    @Override
    public String getOperationName() {
        return "Перевод средств";
    }
}
